//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package 力扣.题库.滑动窗口.定长滑动窗口;

import java.util.HashMap;

public class demo_2461 {
    public demo_2461() {
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 5, 4, 2, 9, 9, 9};
        System.out.println(maximumSubarraySum(nums, 3));
    }

    public static long maximumSubarraySum(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap();
        int l = 0;
        long max = 0L;
        long sum = 0L;
        int n = nums.length;

        for(int i = 0; i < n; ++i) {
            sum += (long)nums[i];
            map.merge(nums[i], 1, Integer::sum);
            if (i >= k - 1) {
                if (map.size() == k) {
                    max = Math.max(max, sum);
                }

                int out = nums[l];
                ++l;
                sum -= (long)out;
                int c = (Integer)map.get(out);
                if (c > 1) {
                    map.put(out, c - 1);
                } else {
                    map.remove(out);
                }
            }
        }

        return max;
    }
}
